package validators;

import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

@FacesValidator("validators.PasswordValidator")
public class PasswordValidator implements Validator {

	private Pattern pattern;
	private Matcher matcher;

	private Pattern pattern2;
	private Matcher matcher2;

	ResourceBundle bundle = ResourceBundle.getBundle(
			"languageSettings.language", FacesContext.getCurrentInstance()
					.getViewRoot().getLocale());
	
	private static final String PASSWORD_PATTERN = "^[a-zA-Z0-9]{6,20}$";

	private static final String PASSWORD_PATTERN2 = "((?=.*[a-z])(?=.*[0-9]).{6,20})";

	public PasswordValidator() {
		pattern = Pattern.compile(PASSWORD_PATTERN);
		pattern2 = Pattern.compile(PASSWORD_PATTERN2);
	}

	@Override
	public void validate(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {

		matcher = pattern.matcher((CharSequence) value);
		matcher2 = pattern2.matcher((CharSequence) value);

		if (!matcher.matches()) {

			FacesMessage message = new FacesMessage(bundle.getString("Validators_PasswordValidator_Error"));
			message.setSeverity(FacesMessage.SEVERITY_ERROR);
			throw new ValidatorException(message);
		} else {
			if (!matcher2.matches()) {

				FacesMessage message = new FacesMessage(bundle.getString("Validators_PasswordValidator_Error"));
				message.setSeverity(FacesMessage.SEVERITY_ERROR);
				throw new ValidatorException(message);
			}
		}

	}

}
